<template>
  <el-card >
     <!-- 面板屑导航 -->
    <el-breadcrumb separator="/" style="margin-bottom: 40px">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>个人中心</el-breadcrumb-item>
      <el-breadcrumb-item>重置密码</el-breadcrumb-item>
    </el-breadcrumb>

    <el-form :model="pwdForm" :rules="rules" ref="pwdRef" label-width="100px" style="width: 500px">
      <el-form-item label="原密码" prop="old_pwd">
        <el-input type="password" v-model="pwdForm.old_pwd"></el-input>
      </el-form-item>
      <el-form-item label="新密码" prop="new_pwd">
        <el-input type="password" v-model="pwdForm.new_pwd"></el-input>
      </el-form-item>
      <el-form-item label="确认新密码" prop="re_pwd">
        <el-input type="password" v-model="pwdForm.re_pwd"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="changePwd">修改密码</el-button>
        <el-button @click="$refs.pwdRef.resetFields()">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>
<script>
import { reqUpdatePwd } from '@/api/user'
export default {
  name: 'UserPassword',
  data () {
    // 校验两次新密码的自定义校验规则
    const checkpwdRepeat = (rule, value, cb) => {
      if (value !== this.pwdForm.new_pwd) {
        cb(new Error('两次新密码输入不一致'))
      } else {
        cb()
      }
    }
    return {
      pwdForm: {
        old_pwd: '',
        new_pwd: '',
        re_pwd: ''
      },
      rules: {
        old_pwd: [
          { required: true, message: '原密码不能为空', trigger: ['change', 'blur'] },
          { pattern: /^\S{6,15}$/, message: '必须是6-15位非空字符', trigger: ['change', 'blur'] }
        ],
        new_pwd: [
          { required: true, message: '新密码不能为空', trigger: ['change', 'blur'] },
          { pattern: /^\S{6,15}$/, message: '必须是6-15位非空字符', trigger: ['change', 'blur'] }
        ],
        re_pwd: [
          { required: true, message: '确认密码不能为空', trigger: ['change', 'blur'] },
          { pattern: /^\S{6,15}$/, message: '必须是6-15位非空字符', trigger: ['change', 'blur'] },
          { validator: checkpwdRepeat, trigger: ['change', 'blur'] }
        ]
      }
    }
  },
  methods: {
    // 更新密码
    changePwd () {
      // 1. 预校验
      this.$refs.pwdRef.validate(async boo => {
        if (boo) {
          // 2.发送请求
          const { data } = await reqUpdatePwd(this.pwdForm)
          // 3. 提示
          if (data.code !== 0) return this.$message.error(data.message)
          this.$message.success(data.message)
          // 4. 清除token
          localStorage.removeItem('tokenKey')
          // 5. 清除vuex中个人信息
          this.$store.commit('user/setUserInfo', {})
          // 6. 跳转到登录页
          this.$router.push('/login')
        }
      })
    }
  }
}
</script>
